class FollowupRecord < ApplicationRecord
  
  belongs_to :company, class_name: "Company", foreign_key: "companies_id"
  belongs_to :contact, class_name: "Contact", foreign_key: "contacts_id"
  belongs_to :followup_employee, class_name: "Employee", foreign_key: "followup_employee_code", primary_key: "emp_code", optional: true # 创建第一条时必须要加
  belongs_to :create_employee, class_name: "Employee", foreign_key: "creator_id", primary_key: "emp_code", optional: true # 创建第一条时必须要加

  validates :companies_id, presence: true
  validates :followup_time, presence: true
  validates :followup_employee_code, length: { maximum: 10 }
  validates :contact_channel, presence: true, inclusion: { in: [0, 1, 2, 3] }
  validates :followup_phase, presence: true, length: { maximum: 10 }
  validates :followup_status, presence: true, inclusion: { in: [0, 1] }
  validates :note, length: { maximum: 200 }

  default_scope { where("is_delete = 0") }

  # 查询出跟进任务列表数据
  def query_followup_records_list
    FollowupRecord.find_by_sql("select 
      f.id,
      f.followup_status as '跟进状态',
      f.followup_time as '安排时间',
      a.emp_name_cn as '安排人',
      f.created_at as '创建时间',
      b.emp_name_cn as '创建人',
      c.name as '联系人',
      f.contact_channel as '联系方式',
      f.followup_phase as '跟进阶段',
      f.note as '备注'
      from followup_records f
      left join employees a on f.followup_employee_code = a.emp_code
      left join employees b on f.creator_id = b.emp_code
      left join contacts c on f.contacts_id = c.id
      where f.companies_id = 1")
  end
  

end
